package com.todo.pro.auditlog.handler;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;

public class AuditLogTableCreator {

    private final static String sqlTemplate = "CREATE TABLE %s (" +
            "id bigint(20) NOT NULL AUTO_INCREMENT," +
            "table_name varchar(50) DEFAULT NULL," +
            "column_name varchar(50) DEFAULT NULL," +
            "primary_key bigint(20) DEFAULT NULL," +
            "parent_id bigint(20) DEFAULT NULL," +
            "new_value varchar(1000) DEFAULT NULL," +
            "old_value varchar(1000) DEFAULT NULL," +
            "operation varchar(20) DEFAULT NULL," +
            "create_time datetime DEFAULT NULL," +
            "create_clerk bigint(20) DEFAULT NULL," +
            "PRIMARY KEY (id)) ENGINE=InnoDB;";

    private String defaultTableName;

    private String preTableName;

    private String currentValidTableName;

    private Boolean splitEnable;

    public AuditLogTableCreator(Boolean splitEnable, String defaultTableName, String preTableName) {

        this.splitEnable = splitEnable;
        this.defaultTableName = defaultTableName;
        this.preTableName = preTableName;

        currentValidTableName = getCurrentTableName();
    }

    String getCurrentTableName() {
        if (splitEnable) {
            Calendar calendar = Calendar.getInstance();
            String calendarMonth;
            if (calendar.get(Calendar.MONTH) < 9) {
                calendarMonth = "0" + (calendar.get(Calendar.MONTH) + 1);
            } else {
                calendarMonth = String.valueOf((calendar.get(Calendar.MONTH) + 1));
            }
            return preTableName + calendar.get(Calendar.YEAR) + calendarMonth;
        } else {
            return defaultTableName;
        }

    }

    String createNew(Connection connection) {
        try {
            String tableNameByNowDate = getCurrentTableName();
            Statement statement = connection.createStatement();
            statement.execute(String.format(sqlTemplate, tableNameByNowDate));
            statement.close();
            currentValidTableName = tableNameByNowDate;
            return tableNameByNowDate;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    String getCurrentValidTableName() {
        return currentValidTableName;
    }

    Boolean getSplitEnable() {
        return splitEnable;
    }
}
